"use strict"

const bag = 70;
const unit = 1000;
const mvc = require('cosjs.mvc');
const random = mvc.library.require('random');
const promise = mvc.library.require('promise');
//id,num,filter
exports.group = function (id) {
    let num = 1, next = 1, filter
    if (typeof arguments[next] === 'number') {
        num = arguments[next];
        next++;
    }
    filter = arguments[next];
    if (Array.isArray(id)) {
        return igroup_parse_array(id, num, filter);
    } else if (id) {
        let itemGroup = mvc.config('itemGroup', id);
        if (!itemGroup) {
            return promise.error("config_not_exist", ['itemGroup', id]);
        }
        let arr = Array.isArray(itemGroup) ? itemGroup : itemGroup['rows'] || itemGroup['Coll'];
        if (arr[0].type == 1) {
            return igroup_parse_array(arr, num, filter);
        } else {
            return igroup_parse_item(id, num, filter);
        }
    } else {
        return promise.error("itemGroup_id_empty", id);
    }
}

//解析物品相对概率组
function igroup_parse_item(id, num, filter) {
    let iType = mvc.config("iTypes", String(id).substr(0, 2));
    if (!iType || iType['bag'] != bag) {
        return promise.error(null, { "id": id, "num": num, "key": 0 });
    }
    let itemGroup = mvc.config('itemGroup', id);
    if (!itemGroup) {
        return promise.error("config_not_exist", ['itemGroup', id]);
    }
    let arr = Array.isArray(itemGroup) ? itemGroup : itemGroup['rows'] || itemGroup['Coll'];
    let k = random.Relative(arr, 'val', filter);
    if (k === false || !arr[k]) {
        return promise.error("itemGroup_Relative_error", id);
    }
    let item = arr[k];
    return promise.error(null, { "id": item["key"], "num": item["num"] * num, "key": parseInt(k) });
}

//解析数组
function igroup_parse_array(arr, num, filter) {
    let result = [];
    for (let i = 0; i < arr.length; i++) {
        let v = arr[i];
        if (v.hasOwnProperty("val") && !random.Probability(v.val, unit)) {
            continue;
        }
        let k = v.id || v.key;
        if (v.type == 1) {
            result.push({ "id": v["key"], "num": v["num"] * num, "key": i });
        } else {
            let { err, ret } = igroup_parse_item(k, v['num'] * num, i);
            if (err) {
                return promise.error(err, ret);
            } else if (ret) {
                result.push(ret);
            }
        }
    }
    return promise.error(null, result);
}
